package com.tywj.panda.customer.common.tool

import androidx.lifecycle.LifecycleOwner
import com.tywj.lib.core.common.extension.applyScheduler
import com.tywj.lib.lifecycle.extension.attachToLifecycle
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/18
 *     desc   : rx工具类
 *     version: 1.0.0
 * </pre>
 */
object RxTool {

    /**
     * 倒计时
     * @param count 倒计时数量
     *
     */
    fun countDown(
        count: Int,
        owner: LifecycleOwner,
        onNext: ((Int) -> Unit)? = null,
        onError: ((Throwable) -> Unit)? = null,
        onComplete: (() -> Unit)? = null
    ): Disposable? {
        if (count <= 0) {
            onComplete?.invoke()
            return null
        }

        onNext?.invoke(count)
        val disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .map { count - it.toInt() }
            .applyScheduler()
            .take((count + 1).toLong())
            .subscribe({
                onNext?.invoke(it)
            }, {
                onError?.invoke(it)
            }, {
                onComplete?.invoke()
            })
        disposable.attachToLifecycle(owner)
        return disposable
    }

}